﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DataAccess;
using System.Data;
namespace XuaNhapKho
{
    public partial class KhachHang : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Session["User"] == null)
                {
                    Response.Redirect("/Default.aspx");
                }
                loadGridView();
                loadData();
            }
        }

        private void loadData()
        {
            grvKhachHang.DataSource = KhachHangDAO.GetAll();
            grvKhachHang.DataBind();
        }

        private void loadGridView()
        {
            if (Request.QueryString["id"] != null)
            {
                int id = int.Parse(Request.QueryString["id"].ToString());
                DataTable dt = KhachHangDAO.GetBy(id).Tables[0];

                foreach (DataRow rows in dt.Rows)
                {
                    txtTenKhachHang.Text = rows["TenKhachHang"].ToString();
                    txtDiaChi.Text = rows["DiaChi"].ToString();
                    txtSoDienThoai.Text = rows["SoDienThoai"].ToString();
                    txtEmail.Text = rows["Email"].ToString();
                }
            }
        }

        protected void lbtnEdit_Command(object sender, CommandEventArgs e)
        {
            int id = int.Parse(e.CommandArgument.ToString());
            Response.Redirect("/KhachHang.aspx?id=" + id);
        }

        protected void lbtnRemove_Command(object sender, CommandEventArgs e)
        {
            int id = int.Parse(e.CommandArgument.ToString());
            KhachHangDAO.Delete(id);
            Response.Redirect("/KhachHang.aspx");
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            string tenkhachhang = txtTenKhachHang.Text;
            string diachi = txtDiaChi.Text;
            string sodienthoai = txtSoDienThoai.Text;
            string email = txtEmail.Text;
            if (Request.QueryString["id"] == null)
            {
                KhachHangDAO.Insert(tenkhachhang, email, diachi, sodienthoai);
                Response.Redirect("/KhachHang.aspx");
            }
            else
            {
                int id = int.Parse(Request.QueryString["id"].ToString());
                KhachHangDAO.Update(id,tenkhachhang,email,diachi,sodienthoai);
                Response.Redirect("/KhachHang.aspx");
            }
        }

        protected void grvKhachHang_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grvKhachHang.PageIndex = e.NewPageIndex;
            loadData();
        }

    }
}